package com.sunday.gateway.mock.security.webflux.login.handler;

import com.sunday.common.core.remoting.rest.response.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

@Slf4j
public class JsonServerAuthenticationSuccessHandler implements ServerAuthenticationSuccessHandler {

    /**
     * 应用程序身份验证成功时调用
     */
    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        RestResponse<String> restResponse = RestResponse.ok();

        log.info("登录成功, {} ", authentication.getPrincipal());
        // 登录成功后可以放入一些参数到session中
        ServerHttpResponse response = webFilterExchange.getExchange().getResponse();
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        DataBufferFactory dataBufferFactory = response.bufferFactory();
        DataBuffer buffer = dataBufferFactory.wrap(restResponse.toJson().getBytes(Charset.defaultCharset()));
        return response.writeWith(Mono.just(buffer)).doOnError((_) -> DataBufferUtils.release(buffer));
    }
}